package com.juku2024.juku.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import com.juku2024.juku.R
import com.juku2024.juku.callback.OnNoDoubleClickListener
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.NoticeDetailEntity
import com.juku2024.juku.model.Notice
import com.juku2024.juku.tools.*
import io.reactivex.disposables.Disposable

/**
 * 通知框
 */
class NoticeDialog(context: Context, private val notice: NoticeDetailEntity?) : Dialog(context, R.style.CommonDialogStyle) {

    companion object {

        fun showNotifyDialog(context: Context, notice: Notice?){
            // 通知开关 0关闭 1开启
            if (notice?.noticeSwitch == false) {
                return
            }
            // 通知版本号
            val version = notice?.version?:0
            // 查本地是否存储过通知
            val dao = NoteRoomUtils.getInstance().noticeDao()
            var model: NoticeDetailEntity? = dao.query(version)
            if (model == null) {
                if (notice?.notice == null) {
                    return
                } else {
                    model = notice.notice
                    model?.version = version
                    dao.deleteAll()
                    dao.insert(model)
                }
            }
            // 本地版本号与通知版本号相同，同时不再提醒的版本号也跟通知版本号相同
            if (model?.version == version) {
                if (SPUtil.instance.isNoMoreDisplay == version) { // 用户点击了不再提醒
                    return
                }
            } else {
                model?.version = version
                model = notice?.notice
                dao.deleteAll()
                dao.insert(model)
            }

            val dialog = NoticeDialog(context, model)
            dialog.show()
        }

    }

    private lateinit var title: TextView
    private lateinit var tvContent: TextView
    private lateinit var tvNoticeCbTip: TextView
    private lateinit var btnAlwaysShow: TextView
    private lateinit var btnRight: TextView
    private lateinit var cbNotice: AppCompatCheckBox
    private lateinit var tvPercent: TextView
    private lateinit var pbUpdate: ProgressBar

    @Suppress("DEPRECATION")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.decorView?.setPadding(0, 0, 0, 0)
        val params = window?.attributes
        val width = context.resources.getDimensionPixelSize(R.dimen.d_300)
        params?.width = width
        params?.height = ViewGroup.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        if (notice == null) {
            dismiss()
            return
        }
        setContentView(R.layout.dialog_notice)
        // 默认先不允许取消弹窗
        isAllowCancelTouchOutSize(false)

        btnAlwaysShow = findViewById(R.id.btnAlwaysShow)
        btnRight = findViewById(R.id.btnRight)
        title = findViewById(R.id.tvNoticeTitle)
        tvContent = findViewById(R.id.tvNoticeContent)
        tvNoticeCbTip = findViewById(R.id.tvNoticeCbTip)
        cbNotice = findViewById(R.id.cbNotice)
        pbUpdate = findViewById(R.id.pbUpdate)
        tvPercent = findViewById(R.id.tvPercent)

        cbNotice.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                SPUtil.instance.isNoMoreDisplay = notice.version
            } else {
                SPUtil.instance.isNoMoreDisplay = 0
            }
        }

        // 设置标题
        title.text = notice.title?:"提示"
        // 设置按钮文本
        btnAlwaysShow.text = notice.btnTitle?:"知道了"
        // 设置可滑动
        tvContent.movementMethod = ScrollingMovementMethod()
        // 开始响应点击事件
        tvContent.movementMethod = LinkMovementMethod.getInstance()
        // 加载富文本内容
        if (!TextUtils.isEmpty(notice.txt)) {
            tvContent.text = if (Build.VERSION.SDK_INT >= 24)
                Html.fromHtml(notice.txt, Html.FROM_HTML_MODE_COMPACT)
            else
                Html.fromHtml(notice.txt)
        }

        // 右侧按钮点击事件
        btnRight.setOnClickListener {
            dismiss()
        }

        showNotification(notice)
    }

    // 倒计时
    private var disposable: Disposable? = null
    private fun showNotification(notice: NoticeDetailEntity) {
        // 通知没有"取消"按钮
        btnRight.visibility = View.GONE
        // 通知的"不再显示"提示要根据后台来控制
        val visibility = if (notice.neverNotify == 0) View.GONE else View.VISIBLE
        cbNotice.visibility = visibility
        tvNoticeCbTip.visibility = visibility

        var isWaitDelay = false
        // 判断是否需要倒计时
        if (notice.waitingTime > 0) { // 显示倒计时
            isWaitDelay = true
            btnAlwaysShow.setBackgroundResource(R.drawable.shape_notice_countdown_normal)
            btnAlwaysShow.setTextColor(Color.parseColor("#cccccc"))
            btnAlwaysShow.text = notice.btnTitle + "(${notice.waitingTime})"
            disposable = RxUtils.interval(0, notice.waitingTime * 1L + 1, 0, 1000L) {
                btnAlwaysShow.text = notice.btnTitle + "（${notice.waitingTime - it}s）"
                if (it >= notice.waitingTime) {
                    isWaitDelay = false
                    isAllowCancelTouchOutSize(true)
                    btnAlwaysShow.text = notice.btnTitle
                    btnAlwaysShow.setTextColor(Color.parseColor("#FFFFFF"))
                    btnAlwaysShow.setBackgroundResource(R.drawable.shape_notice_countdown)
                }
            }
        } else {
            isAllowCancelTouchOutSize(true)
            btnAlwaysShow.setTextColor(Color.parseColor("#FFFFFF"))
            btnAlwaysShow.setBackgroundResource(R.drawable.shape_notice_countdown)
        }

        btnAlwaysShow.setOnClickListener(object : OnNoDoubleClickListener {
            override fun onNoDoubleClick(v: View?) {
                super.onNoDoubleClick(v)
                if (isWaitDelay) return
                // 直接自动下载apk
                if (TextUtils.isEmpty(notice.url)) {
                    dismiss()
                    return
                }
                AppUtils.toWeb(notice.url!!)
                dismiss()
            }
        })
    }


    private fun isAllowCancelTouchOutSize(isAllowCancel: Boolean){
        // 强升不能取消弹窗
        setCancelable(isAllowCancel)
        // 点击外部区域不能取消对话框
        setCanceledOnTouchOutside(isAllowCancel)
    }

}